/**
 * @author Marakhovski Pavel
 * @common JS for jQuery and jQuery UI freamwork.
 * @added_mathod $.dia - creating new empty dialog with default settings.
 * @added_mathod $.jLoading - creating modal dialog whith animated dots and whaiting masage.
 * @added_mathod $.FormData - save form data to cookie
 * @added_mathod $.cookie - set or get or delete data from cookie
 * @added_mathod $.onEnter - click to button by the press enter button
 */

;
(function($) {
	function standardSpeed( speed ) {
		// valid standard speeds
		if ( !speed || typeof speed === "number" || $.fx.speeds[ speed ] ) {
			return true;
		}
		// invalid strings - treat as "normal" speed
		if ( typeof speed === "string" && !$.effects[ speed ] ) {
			return true;
		}
		return false;
	}

	function _normalizeArguments(effect, options, speed, callback) {
		// shift params for method overloading
		if (typeof effect == 'object') {
			if(effect.sp) {
				callback = effect.callback||0;
				speed = null;
				options = effect;
				effect = effect.nm;
			} else {
				callback = options;
				speed = null;
				options = effect;
				effect = options.effect;
			}
		}
		if ($.isFunction(options)) {
			callback = options;
			speed = null;
			options = {};
		}
		if (typeof options == 'number' || $.fx.speeds[options]) {
			callback = speed;
			speed = options;
			options = {};
		}
		if ($.isFunction(speed)) {
			callback = speed;
			speed = null;
		}

		options = options || {};

		speed = speed || options.duration;
		speed = $.fx.off ? 0 : typeof speed == 'number'
		? speed : speed in $.fx.speeds ? $.fx.speeds[speed] : $.fx.speeds._default;

		callback = callback || options.complete;

		return [effect, options, speed, callback];
	}

	$.fn.extend({
		show: function(speed) {
			if ( standardSpeed( speed ) ) {
				return this._show.apply(this, arguments);
			} else {
				var args = _normalizeArguments.apply(this, arguments);
				args[1].mode = 'show';
				return this.effect.apply(this, args);
			}
		}
	});

	if($&&$.fn&&$.fn.button) {
		$.fn.but= function(opt) {
			opt&&opt.icon?$.extend(opt, {
				icons: {
					primary:"ui-icon-"+opt.icon
				}
			}):null;
			return this.button(opt);
		};
		var dialogs= {
			lastNumb:0
		};
		$.dia = function(options) {
			options 	= options || {};
			var id 		= options.id || "auto-dialog-" + (dialogs.lastNumb++) + "-a-id";
			var dialog 	= $("<div id='" + id + "' class='AutoDialog"+(options.addClass?" "+options.addClass:"")+"'></div>").appendTo(options.parent||"body");
			var hideO 	= {
				sp:true,
				nm:'fade',
				callback: function() {
					dialog.trigger('dialogHide');
				}
			};
			var showO 	= {
				sp:true,
				nm:'fade',
				callback: function() {
					dialog.trigger('dialogShow');
				}
			};

			if(typeof(options.hide)=='string') {
				hideO.nm = options.hide;
				delete options.hide;
			}
			if(typeof(options.show)=='string') {
				showO.nm = options.show;
				delete options.show;
			}

			var defaultOptions = {
				width: options.w || "auto",
				height: options.h || "auto",
				modal: options.mod || false,
				draggable: options.drg && true,
				zIndex: options.zInd || 10000,
				title: options.title || "",
				position: options.pos || [200, "top"],
				resizable: (options.res?options.res:false),
				hide: hideO,
				show: showO,
				close: function() {
					if(options.close&&$.isFunction(options.close)){
						options.close();
					}
					dialog.dialog( "destroy" ).remove();
				},
				pos: options.poss || "absolute",
				autoOpen:false
			};

			$.extend(defaultOptions,options);

			dialog.dialog(defaultOptions);
			delete id,hideO,showO,defaultOptions;
			return dialog;
		};
	}

	$.fn.selectOptionFromSelectElem = function() {
		this.each( function() {
			$('select.select',this).each( function() {
				var select		= $(this);
				var selectItem 	= select.data('select');
				var isMultiple 	= select.attr('multiple');
				if(selectItem[0]!="{") {
					$('option',select).each( function(i) {
						console.log(i);
						var option = $(this);
						if(option.val()==selectItem) {
							setTimeout( function() {
								option.attr("selected",true);
							},2000);
							if(!isMultiple) {
								return true;
							}
						}
					});
				}
			});
		});
		return true;
	}
	$.jLoading = function(opts) {
		var opt = {
			msg:"Загрузка",
			time:200,
			minLoadingTime:300,
			colback:false
		};
		function stop(dia) {
			if(window.loadingDialog||(dia&&(window.loadingDialog=dia))) {
				$('span.loadingBar',window.loadingDialog).data('run',false);
				try {
					window.loadingDialog.dialog('close');
					delete window.loadingDialog;
				} catch(e) {}
			}
		}

		if(typeof(opts)=="string"&&opts=='stop') {
			if(!window.loadingDialog)
				window.loadingDialog=$('#loadingDialog');
			if(window.loadingDialog.length==0||!window.loadingDialog.data)
				return false;
			var start_time = window.loadingDialog.data('startTime');
			var now = (new Date()).getTime();
			var delta = now-start_time;
			//false&&
			if(delta>0&&delta<opt.minLoadingTime&&(opt.minLoadingTime-delta)>50) {
				setTimeout(stop,opt.minLoadingTime-delta);
			} else {
				stop();
			}
		} else {
			if($('#loadingDialog').length!=0)return false;
			$.extend(opt,opts);
			var msg = opt.msg;
			var dia = $.dia({
				mod:true,
				position:'center',
				width:'auto',
				height:'auto',
				minHeight:10,
				modal:true,
				resizable:false,
				autoOpen:false
			}).html('<div>'+msg+'<span class="loadingBar">.</span></div>');
			dia.attr('id','loadingDialog').bind('dialogclose',function(e){
				if(opt.colback&&$.isFynction(colback)){
					colback();
				}
			});
			$('.ui-dialog-titlebar',dia.parent()).remove();
			var dotSpan = $('span.loadingBar',dia);
			dotSpan.data('dotLength',0).data('run',true);
			var dots = ['','.','..','...']
			function animDot() {
				var i = dotSpan.data('dotLength');
				dotSpan.text(dots[i]);
				if(i==3) {
					i=0;
				} else {
					i++;
				}
				dotSpan.data('dotLength',i);
				if(dotSpan.data('run')) {
					setTimeout(animDot,opt.time);
				}
			}

			animDot();
			dia.dialog('open');
			dia.data('startTime',(new Date()).getTime());
			window.loadingDialog = dia;
		}
	}
	$.jAlert = function(msg) {
		var dia = $.dia({
			position:'center',
			width:'auto',
			height:'auto',
			minHeight:10,
			modal:true,
			resizable:false,
			autoOpen:false,
			title:"Внимание!",
			buttons: {
				"Хорошо": function() {
					$(this).dialog("close");
				}
			}
		}).addClass('ui-state-highlight').html('<div class="w_300 ta_j">'+msg+'</div>');
		$('.ui-dialog-titlebar',dia.parent()).addClass('ui-state-default');
		dia.dialog('open');
	}
	$.jConfirm = function(msg,calback) {
		if(!$.isFunction(calback))
			return false;
		var dia = $.dia({
			position:'center',
			width:'auto',
			height:'auto',
			minHeight:10,
			modal:true,
			resizable:false,
			autoOpen:false,
			title:"Внимание!",
			buttons: {
				"Нет": function() {
					$(this).dialog("close");
					calback(false);
				},
				"Да": function() {
					$(this).dialog("close");
					calback(true)
				}
			}
		}).addClass('ui-state-highlight').html('<div class="w_300 ta_j">'+msg+'</div>');
		$('.ui-dialog-titlebar',dia.parent()).addClass('ui-state-default');
		dia.dialog('open');
	}
	$.jError = function(msg) {
		var dia = $.dia({
			position:'center',
			width:'auto',
			height:'auto',
			minHeight:10,
			modal:true,
			resizable:false,
			autoOpen:false,
			title:"Ошибка!"
		}).addClass('ui-state-error').html('<div class="w200"><p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>'+msg+'</p></div>');
		$('.ui-dialog-titlebar',dia.parent()).addClass('ui-state-error');
		dia.dialog('open');
	}
	/**
	 * Cookie plugin
	 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
	 */
	jQuery.cookie = function(name, value, options) {
		if (typeof value != 'undefined') { // name and value given, set cookie
			options = options || {};
			if (value === null) {
				value = '';
				options.expires = -1;
			}
			var expires = '';
			if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
				var date;
				if (typeof options.expires == 'number') {
					date = new Date();
					date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
				} else {
					date = options.expires;
				}
				expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
			}
			var path = options.path ? '; path=' + options.path : '';
			var domain = options.domain ? '; domain=' + options.domain : '';
			var secure = options.secure ? '; secure' : '';
			document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
		} else { // only name given, get cookie
			var cookieValue = null;
			if (document.cookie && document.cookie != '') {
				var cookies = document.cookie.split(';');
				for (var i = 0; i < cookies.length; i++) {
					var cookie = jQuery.trim(cookies[i]);
					// Does this cookie string begin with the name we want?
					if (cookie.substring(0, name.length + 1) == (name + '=')) {
						cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
						break;
					}
				}
			}
			return cookieValue;
		}
	};
	$.fn.FormData = function(opt) {
		var id = this[0].id;
		if(!id)
			return false;
		var isInit = $.cookie(id+"_isInit");
		var def = {
			lifeTime:2400
		};
		if(typeof opt =='string') {
			if(opt=='load') {
				var d = this.serializeArray();
				c:
				for(var i=0;i<d.length;i++) {
					var o = $('[name="'+d[i].name+'"][type][type!="radio"]',this);
					var dontLoad = o.data('not-save')||(o.attr('type')=='password');
					if(dontLoad)
						continue c;
					o.val(($.cookie(d[i].name)||""));
				}
			} else if(opt=='delete') {
				$.cookie(id+"_isInit",null);
				var d = this.serializeArray();
				for(var i=0;i<d.length;i++) {
					$.cookie(d[i].name,null);
				}
			}
		} else {
			$.extend(def,opt);
			$.cookie(id+"_isInit","true");
			var d = this.serializeArray();
			c:
			for(var i=0;i<d.length;i++) {
				var o = $('[name="'+d[i].name+'"][type][type!="radio"]');
				var dontSave = o.data('not-save')||(o.attr('type')=='password');
				if(dontSave)
					continue c;
				$.cookie(d[i].name,d[i].value, {
					expires:def.lifeTime
				});
			}
			if($.isFunction(opt)) {
				opt();
			}
		}
	}
	$.fn.onEnter = function(button,calback,id) {
		if(button&&!$.isFunction(button)) {
			button = typeof button!="string"&&button.length>0?button:$(button);
			id = id || this.attr('id');
			if(id&&id!='') {
				$('body').delegate(id,'keyup', function(e) {
					if (e.keyCode == 13) {
						var o = $(e.currentTarget);
						button.click();
						calback&&$.isFunction(calback)?calback(e):null;
						return false;
					}
				});
			} else {
				this.keyup( function(e) {
					if (e.keyCode == 13) {
						var o = $(e.currentTarget);
						button.click();
						calback&&$.isFunction(calback)?calback(e):null;
						return false;
					}
				});
			}
		} else {
			this.keyup( function(e) {
				if (e.keyCode == 13) {
					button();
					return false;
				}
			});
		}
	}
	$.onEnter = function(id,button) {
		$.fn.onEnter(button,null,id);
	}
	/* Created by jankoatwarpspeed.com */

	$.fn.formToWizard = function(options) {
		options = $.extend({
			submitButton: "",
			hideEffect:"slide",
			showEffect:"slide",
			animateDuration:500
		}, options);

		var element 		= this;
		element.wrap("<div class='ui-wizard-widget' style='overflow: hidden;'></div>");
		var widget 			= element.parent();
		var steps 			= $(element).find("fieldset");
		var count 			= steps.size();
		var submmitButton 	= typeof(options.submitButton)=='string'?$(options.submmitButtonName):options.submmitButtonName;
		submmitButton.hide();
		var ul = $("<div class='steps'></div>").insertBefore(element);
		steps.each( function(i) {
			var o = $(this);
			o.wrap("<div class='step ui-widget-content' id='step" + i + "' style='border-top:none'></div>");
			o.append("<p id='step" + i + "commands'></p>");
			var name = $(this).find("legend").html();
			ul.append("<div id='stepDesc" + i + "' class='stepTitle cell ui-state-default"+(i==0?" ui-state-active":"")+"'>Шаг " + (i + 1) + "<div>" + name + "</div></div>");

			if(i == 0) {
				createNextButton(i);
				selectStep(i,1);
			} else if(i == count - 1) {
				$("#step" + i).hide();
				createPrevButton(i);
			} else {
				$("#step" + i).hide();
				createPrevButton(i);
				createNextButton(i);
			}
		});
		this.delegate('div.prev , div.next','click', function() {
			var o 			= $(this);
			var i 			= o.data('i');
			var stepName 	= "step" + i;
			var direction	= o.hasClass('next')?-1:1;
			var errorInStep = element.validationEngine('validate');
			if(!errorInStep)return false;
			$("#" + stepName).hide(options.hideEffect, {
				direction:(direction==1?"right":"left")
			},options.animateDuration, function() {
				$("#step" + (i-1*direction)).show(options.showEffect, {
					direction:(direction==1?"left":"right")
				},options.animateDuration,function(){
				});
				submmitButton.hide('fade');
				if(direction==-1&&i + 2 == count)
					submmitButton.show('fade');
				selectStep(i-1*direction);
			});
		});
		function createPrevButton(i) {
			var stepName = "step" + i;
			$("<div id='" + stepName + "Prev' class='prev' data-i='"+i+"'>Назад</div>").appendTo("#" + stepName + "commands").but({
				icon:"circle-arrow-w"
			});
		}

		function createNextButton(i) {
			var stepName = "step" + i;
			$("<div id='" + stepName + "Next' class='next' data-i='"+i+"'>Вперёд</div>").appendTo("#" + stepName + "commands").but({
				icons: {
					secondary:"ui-icon-circle-arrow-e"
				}
			});
		}

		function selectStep(i,first) {
			var prev 		= $("div.ui-state-active",ul);
			var prev_pos 	= prev.position();
			var next 		= jQuery('#stepDesc'+i);
			var next_pos 	= next.position();

			prev.css('border-bottom','1px solid').removeClass('ui-state-active');
			if(first){
				next.addClass("ui-state-active").css('border-bottom','none');
			}else{
				var mask = prev.clone().removeAttr('id').css('opacity','0').addClass('ui-state-active').appendTo('.steps');
				mask.css({
					width:mask.width(),
					height:mask.height(),
					'position':'absolute',
					'top':prev_pos.top,
					'left':prev_pos.left,
					opacity:1
				}).html('').animate({
					left:next_pos.left,
					width:next.width()
				},options.animateDuration, function() {
					next.addClass("ui-state-active").css('border-bottom','none');
					$(this).hide('fade', function() {
						$(this).remove()
					});
				});
			}
		}
		return element;
	}
})(jQuery);

function strip_tags(input, allowed) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Tomasz Wesolowski
    // +      input by: Evertjan Garretsen
    // +    revised by: Rafał Kukawski (http://blog.kukawski.pl/)
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'
    // *     example 5: strip_tags('1 <br/> 1');
    // *     returns 5: '1  1'
    // *     example 6: strip_tags('1 <br/> 1', '<br>');
    // *     returns 6: '1  1'
    // *     example 7: strip_tags('1 <br/> 1', '<br><br/>');
    // *     returns 7: '1 <br/> 1'
    allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}